package android.slc.box.core.widget.grid;

import javafx.scene.Node;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.RowConstraints;

import java.util.List;

/**
 * 自动平分网格布局
 */
public class SlcLinearLayout extends GridPane {

    private static final String LAYOUT_WEIGHT = "slc-layout-weight";

    public static void setLayoutWeight(Node child, Double value) {
        /**/
        setConstraint(child, LAYOUT_WEIGHT, value);
    }

    public static Double getLayoutWeight(Node child) {
        return (Double) getConstraint(child, LAYOUT_WEIGHT);
    }

    private static void setConstraint(Node node, Object key, Object value) {
        if (value == null) {
            node.getProperties().remove(key);
        } else {
            node.getProperties().put(key, value);
        }
        if (node.getParent() != null) {
            node.getParent().requestLayout();
        }
    }

    private static Object getConstraint(Node node, Object key) {
        if (node.hasProperties()) {
            Object value = node.getProperties().get(key);
            if (value != null) {
                return value;
            }
        }
        return null;
    }

    @Override
    protected void layoutChildren() {
        formatColumn(getChildren());
        super.layoutChildren();
    }

    /**
     * 格式化列
     *
     * @param children
     */
    private void formatColumn(List<Node> children) {
        int nodeCount = children.size();
        int columnConstraintCount = getColumnConstraints().size();
        if (nodeCount > columnConstraintCount) {
            for (int i = 0; i < nodeCount - columnConstraintCount; i++) {
                ColumnConstraints constraints = new ColumnConstraints();
                getColumnConstraints().add(constraints);
            }
        } else if (nodeCount < columnConstraintCount) {
            getColumnConstraints().subList(nodeCount, columnConstraintCount).clear();
        }
        getRowConstraints().add(new RowConstraints());
        double sunWeight = 0;
        for (Node child : children) {
            Double weight = (Double) child.getProperties().get(LAYOUT_WEIGHT);
            if (weight != null) {
                sunWeight += weight;
            }
        }
        List<ColumnConstraints> columnConstraintsList = getColumnConstraints();
        for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++) {
            Node node = children.get(nodeIndex);
            Double weight = (Double) node.getProperties().get(LAYOUT_WEIGHT);
            ColumnConstraints columnConstraints = columnConstraintsList.get(nodeIndex);
            if (weight != null) {
                columnConstraints.setPercentWidth(100 * weight / sunWeight);
            }
            GridPane.setConstraints(node, nodeIndex, 0);
        }
    }
}
